<script type="text/jsx">
export default {
  name: 'AbstractInput',

  props: {
    data: {
      type: Object,
      default: () => ({})
    },
    text: {
      type: [String, Number],
      default: null
    },
    value: {
      type: [String, Number],
      default: null
    },
    flex: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      isEdit: false,
      loading: false
    }
  },

  methods: {
    focus() {
      this.isEdit = true
      if (this.text) this.$emit('input', this.text)
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    },

    blur() {
      if (this.value != this.text) {
        this.loading = true
        this.$emit('submit', {
          value: this.value,
          callback: () => {
            this.isEdit = false
            this.loading = false
          },
          success: () => {
            this.isEdit = false
          },
          end: () => {
            this.loading = false
          }
        })
      } else {
        this.isEdit = false
      }
    },

    inputChange(e) {
      this.$emit('input', e)
    }
  },

  render() {
    const { $scopedSlots } = this
    if (this.isEdit) {
      return (
        <el-input
          v-loading={this.loading}
          value={this.value}
          ref="input"
          size="small"
          on-input={this.inputChange}
          on-blur={this.blur}
          {...this.data}
        >
          {$scopedSlots.default && $scopedSlots.default()}
        </el-input>
      )
    } else {
      return (
        <div style={{ display: this.flex && 'flex' }}>
          <span style={{ flex: this.flex && '1' }}>
            {this.text || this.value}
          </span>
          <el-button type="text" size="small" on-click={this.focus}>
            修改
          </el-button>
        </div>
      )
    }
  }
}
</script>
